﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Windows.Forms;
using SO_DataFetcher.PubFunctions;
using SO_DataFetcher.PubFunctions.SqlScripts;

namespace SO_DataFetcher.Forms
{
    public partial class FrmScriptManager : Form
    {
        private ScriptStruct _tempScript = new ScriptStruct();
        private ScriptStruct _oldScript = new ScriptStruct();
        private string _scriptId = string.Empty;
        private string _scriptIndex = string.Empty;
        private string _operateType = string.Empty;

        public FrmScriptManager()
        {
            InitializeComponent();

            SetControlReadOnly(true);
        }

        private void SetControlReadOnly(bool flag)
        {
            this.txtFile.ReadOnly = flag;
            this.txtId.ReadOnly = flag;
            this.listParaments.Enabled = !flag;
            this.btnParamentAdd.Enabled = !flag;
            this.btnParamentEdit.Enabled = !flag;
            this.btnParamentDelete.Enabled = !flag;
            this.btnSave.Visible = !flag;
        }


        private void FrmScriptManager_Load(object sender, EventArgs e)
        {
           RefreshTreeViewSource();
        }

        private void RefreshTreeViewSource()
        {
            this.treeView1.Nodes.Clear();

            if (PubScripts.Scripts.Count > 0)
            {
                foreach (string key in PubScripts.Scripts.Keys)
                {
                    TreeNode node = new TreeNode(key);
                    node.Tag = PubScripts.Scripts[key];
                    treeView1.Nodes.Add(node);
                }

                this.treeView1.ExpandAll();
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                this.listParaments.Items.Clear();
                TreeNode selectNode = treeView1.SelectedNode;
                ScriptStruct script = (ScriptStruct)selectNode.Tag;
                _tempScript = script;
                _oldScript = script;
                if (!string.IsNullOrEmpty(script.Name))
                {
                    this._scriptId = script.Name;
                    this._scriptIndex = script.Index;
                    this.txtId.Text = script.Name;
                    this.txtFile.Text = script.File;
                    this.listParaments.Items.AddRange((object[])script.Paraments.Split(','));
                }
            }
        }

        private void btnScriptAdd_Click(object sender, EventArgs e)
        {
            SetControlReadOnly(false);

            this.txtId.Text = string.Empty;
            this.txtFile.Text = string.Empty;
            this.listParaments.Items.Clear();
            this._operateType = "Add";
        }

        private void btnScriptEdit_Click(object sender, EventArgs e)
        {
            SetControlReadOnly(false);
            this._operateType = "Edit";
        }

        private void btnScriptDelete_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_scriptId))
            {
                if (MessageBox.Show(_scriptId, @"是否确认删除脚本配置?",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    DataRow[] rows = PubScripts.DataTableScripts.Select("Name='" + _scriptId + "'");
                    if (rows.Any())
                    {
                        foreach (DataRow dataRow in rows)
                        {
                            PubScripts.DataTableScripts.Rows.Remove(dataRow);
                        }

                        PubScripts.SaveDataSetLinks();
                        RefreshTreeViewSource();
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this._tempScript.Name))
                {
                    MessageBox.Show(@"Name值不能为空");
                    return;
                }


                if (string.IsNullOrEmpty(this._tempScript.File))
                {
                    MessageBox.Show(@"File值不能为空");
                    return;
                }

                GetTempScriptParaments();

                switch (_operateType)
                {
                    case "Add":
                        this._tempScript.Index = PubCommon.SetIndex();
                        DataRow dataRow = PubScripts.DataTableScripts.NewRow();
                        dataRow["Index"] = _tempScript.Index;
                        dataRow["Name"] = _tempScript.Name;
                        dataRow["File"] = _tempScript.File;
                        dataRow["subParament"] = _tempScript.Paraments;

                        PubScripts.DataTableScripts.Rows.Add(dataRow);

                        break;
                    case "Edit":

                        if (!IsChanged())
                        {
                            MessageBox.Show(@"数据没有发生改变！");
                            return;
                        }

                        DataRow[] rows = PubScripts.DataTableScripts.Select("Index='" + _scriptIndex + "'");
                        if (rows.Any())
                        {
                            dataRow = rows[0];

                            dataRow["Name"] = _tempScript.Name;
                            dataRow["File"] = _tempScript.File;
                            dataRow["subParament"] = _tempScript.Paraments;
                        }

                        break;
                }

                PubScripts.SaveDataSetLinks();

                RefreshTreeViewSource();
            }
            catch (Exception exception)
            {
                MessageBox.Show("保存错误：" + exception.Message);
                return;
            }

            this.btnSave.Visible = false;
        }


        private bool IsChanged()
        {
            if (!_tempScript.Name.Equals(_oldScript.Name))
                return true;

            if (!_tempScript.File.Equals(_oldScript.File))
                return true;

            if (!_tempScript.Paraments.Equals(_oldScript.Paraments))
                return true;

            return false;
        }

        private void GetTempScriptParaments()
        {
            int i = 0;

            foreach (var item in this.listParaments.Items)
            {
                if (i == 0)
                {
                    _tempScript.Paraments = item.ToString();
                    i++;
                }
                else
                {
                    _tempScript.Paraments = _tempScript.Paraments + "," + item.ToString();
                }
            }
        }

        private void txtId_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtId.Text.Trim()))
            {
                _tempScript.Name = this.txtId.Text.Trim();
            }
        }

        private void txtFile_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtFile.Text.Trim()))
                _tempScript.Name = this.txtFile.Text.Trim();
        }

        private void listParaments_DoubleClick(object sender, EventArgs e)
        {
            if (this.listParaments.SelectedIndex > -1)
            {
                this._paramentId = this.listParaments.SelectedItem.ToString();
            }
        }

        private string _paramentId = string.Empty; 

        private void listParaments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listParaments.SelectedIndex > -1)
            {
                this._paramentId = this.listParaments.SelectedItem.ToString();
            }
        }

        private void btnParamentAdd_Click(object sender, EventArgs e)
        {
            GetTempScriptParaments();
            FrmList frmList = new FrmList("Parament", _tempScript.Paraments.Split(','));
            if (frmList.ShowDialog(this) == DialogResult.OK)
            {
                this.listParaments.Items.Clear();
                if (frmList._keyStrings.Length > 0)
                {
                    foreach (string keyString in frmList._keyStrings)
                    {
                        this.listParaments.Items.Add(keyString);
                    }
                }
            }
        }

        private void btnParamentEdit_Click(object sender, EventArgs e)
        {

        }

        private void btnParamentDelete_Click(object sender, EventArgs e)
        {
            if (this.listParaments.SelectedIndex > -1)
            {
                if (MessageBox.Show(@"确认是否删除当前数据？", _scriptId, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) ==
                    DialogResult.OK)
                {
                    this.listParaments.Items.Remove(this.listParaments.SelectedItem);
                }
            }
        }

    }
}
